package com.luck.easyfoodbatch.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.luck.easyfoodbatch.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName: DBManager
 * @Description: 数据库管理类
 * @author lmw
 * @date 2014-12-2 下午1:38:00
 */
public class DBManager {
	private final int BUFFER_SIZE = 400000;
	public static final String DB_NAME = "area.db"; // 保存的数据库文件名
	public static final String PACKAGE_NAME = "com.luck.easyfoodbatch";
	// 在手机里存放数据库的位置
	public static final String DB_PATH = "/data"
			+ Environment.getDataDirectory().getAbsolutePath() + "/"
			+ PACKAGE_NAME + "/databases";
	private SQLiteDatabase database;
	private Context context;

	public DBManager(Context context) {
		this.context = context;
	}

	/**
	 * 
	 * @Title: openDatabase
	 * @Description: 打开数据库
	 * @author lmw
	 * @param dbfile
	 * @return
	 * @return SQLiteDatabase 返回类型
	 */
	public SQLiteDatabase openDatabase() {
		database = this.openDatabase(DB_PATH + "/" + DB_NAME);
		return database;
	}

	/**
	 * 
	 * @Title: openDatabase
	 * @Description: 打开数据库
	 * @author lmw
	 * @param dbfile
	 * @return
	 * @return SQLiteDatabase 返回类型
	 */
	private SQLiteDatabase openDatabase(String dbfile) {
		try {
			// 判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
			if (!(new File(dbfile).exists())) {
				// 读取数据库文件
				InputStream is = context.getResources().openRawResource(
						R.raw.area);
				if (!new File(DB_PATH).exists()) {
					new File(DB_PATH).mkdirs();
				}

				FileOutputStream fos = new FileOutputStream(dbfile);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
					null);
			return db;
		} catch (FileNotFoundException e) {
			Log.e("Database", "File not found");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("Database", "IO exception");
			e.printStackTrace();
		}
		return null;
	}
}
